package com.qf.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter("/*")
public class LoginFilter implements Filter {

    private List<String> staticResources = Arrays.asList(".js", "webp", ".jpg", ".png", ".css");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //判断uri中是否包含静态的资源
    private boolean isContainsStaticResource(String uri) {
        for(String staticResource: staticResources) {
            if(uri.endsWith(staticResource)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String uri = request.getRequestURI();
        if ("/".equals(uri)) {
            filterChain.doFilter(request,response);
            return;
        }
       // @WebServlet({"/admin/goodsManager.jsp", "/admin/index.jsp", "/admin/sysLogin.jsp"})
        if (uri.contains("/index") || uri.contains("/index.jsp") || uri.contains("/login") || uri.contains("/register")
                || uri.contains("/cart") || uri.contains("/good") || uri.contains("/validate") ||uri.contains("/validate-username")
                || uri.contains("/sms") || uri.contains("/address") ||  uri.contains("/user") ||isContainsStaticResource(uri)
                || uri.contains("/settleCount.jsp") || uri.contains("user") || uri.contains("admin") || uri.contains("/pay")
            || uri.contains("/admin")) {

            filterChain.doFilter(request,response);
            return;
           
        }

        HttpSession session = request.getSession();
        // 获取用户在登录成功之后设置的用户信息
        Object object = session.getAttribute("user");
        if(null != object) {
            filterChain.doFilter(request, response);
            return;
        }

        //4.cookie放行
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("userId".equals(cookie.getName())) {
                    if (null != cookie.getValue()) {
                        filterChain.doFilter(request, response);
                        return;
                    }
                }
            }
        }

        response.sendRedirect("/login.jsp");

    }

    @Override
    public void destroy() {

    }
}
